package org.example.task.controller;


import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.task.converter.DeptConverterMapper;
import org.example.task.model.dto.department.CreateDeptDTO;
import org.example.task.model.dto.department.UpdateDeptDTO;
import org.example.task.model.po.Department;
import org.example.task.model.vo.R;
import org.example.task.model.vo.department.DeptVO;
import org.example.task.service.IDepartmentService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门接口
 *
 * @module 部门接口
 */
@RestController
@RequestMapping("/department")
@RequiredArgsConstructor
public class DepartmentController {
    private final IDepartmentService departmentService;
    private final DeptConverterMapper deptConverterMapper;

    /**
     * 添加部门
     *
     * @param createDeptDTO 表单数据
     * @return 结果
     */
    @PreAuthorize("hasAuthority('dept_create')")
    @PostMapping
    public R addDept(@Valid @RequestBody CreateDeptDTO createDeptDTO) {
        boolean flag = departmentService.addDept(createDeptDTO);
        if (flag) {
            return R.success();
        }
        return R.error("操作失败");
    }

    /**
     * 修改部门
     *
     * @param updateDeptDTO 更新数据
     * @return 结果
     */
    @PreAuthorize("hasAuthority('dept_edit')")
    @PutMapping
    public R modifyDept(@Valid @RequestBody UpdateDeptDTO updateDeptDTO) {
        boolean flag = departmentService.modifyDept(updateDeptDTO);
        if (flag) {
            return R.success();
        }
        return R.error("操作失败");
    }

    /**
     * 删除部门
     *
     * @param deptId 部门id
     * @return 结果
     */
    @PreAuthorize("hasAuthority('dept_delete')")
    @DeleteMapping
    public R deleteDept(@RequestParam Long deptId) {
        boolean flag = departmentService.removeById(deptId);
        if (flag) {
            return R.success();
        }
        return R.error("操作失败");
    }

    /**
     * 获取部门列表
     *
     * @return 部门列表数据
     */
    @PreAuthorize("hasAuthority('dept_list')")
    @GetMapping
    public R<List<DeptVO>> getDeptList() {
        List<Department> list = departmentService.list();
        List<DeptVO> deptVOS = deptConverterMapper.deptToDeptVOList(list);
        return R.success(deptVOS);
    }
}
